package com.jxm.spring.security.security.filters;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jxm.spring.security.security.domain.SysUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: jxm
 * @Description: token 权限过滤器，用于验证Token是否合法
 * @Date: 2021/5/16 20:54
 * @Version: 1.0
 */
public class TokenTAuthenticationFilter extends BasicAuthenticationFilter{

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

   public TokenTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        super.doFilterInternal(request, response, filterChain);

        // 取出Token todo 验证token 过滤器
        String token = request.getHeader("token");
        if (token != null /*&& token.startsWith(JWTConfig.tokenPrefix)*/) {
            token = "user:" + token;
//            SysUserDetails sysUserDetails = JWTTokenUtil.parseAccessToken(token);
            System.out.println("-----------"+redisTemplate);
            String s = redisTemplate.opsForValue().get(token);
            JSONObject jsonObject = JSONObject.parseObject(s);
            SysUserDetails sysUserDetails = jsonObject.toJavaObject(SysUserDetails.class);
            if (sysUserDetails != null) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        sysUserDetails, sysUserDetails.getUserId(), sysUserDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);
    }





}
